﻿using Management.Areas.Control.Models;
using Management.Auxiliary;
using Management.Core.ReportConfig;
using Management.Core.SiliconCutting;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Mvc;

namespace Management.Areas.Control.Controllers
{
    [AdminAuthorize]
    
    public class SiliconCuttingController : Controller
    {
        private SiliconCuttingManager scm = new SiliconCuttingManager();
        //
        // GET: /Control/SiliconCutting/
        [OutputCache(CacheProfile = "YLConfigCache")]
        public ActionResult Index()
        {
            var siliconCuttion = new SiliconCutting();
            System.Reflection.PropertyInfo[] props = typeof(SiliconCutting).GetProperties();
            //var attrs = siliconCuttion.GetType().GetProperties();
            List<SelectListItem> _listItems = new List<SelectListItem>(props.Count());
            List<SelectListItem> UnHasConfigs = new List<SelectListItem>();
            //这里写的不大好，后期再改吧 --tony 2017-7-19
            foreach (System.Reflection.PropertyInfo prop in props)
            {
                object[] attrs = prop.GetCustomAttributes(true);
                foreach (object attr in attrs)
                {
                    DisplayAttribute displayAttr = attr as DisplayAttribute;
                    if (displayAttr != null)
                    {
                        _listItems.Add(new SelectListItem() { Text = displayAttr.Name, Value = prop.Name });
                        UnHasConfigs.Add(new SelectListItem() { Text = displayAttr.Name, Value = prop.Name });
                    }
                }
            }
            ReportConfigManager rcm = new ReportConfigManager();
            int adminid = int.Parse(Session["AdminID"].ToString());
            var configs = rcm.FindList(u => u.AdminID == adminid && u.Model == "ReportConfig");
            if(configs != null && configs.Count() > 0 )
            {
                var tmp = configs.FirstOrDefault().Config;
                ViewBag.configs = tmp;
                List<SelectListItem> HasConfigs = new List<SelectListItem>();
                string[] _configs = configs.FirstOrDefault().Config.Split(',');
                foreach(var _config in _configs)
                {                   
                    foreach(SelectListItem item in UnHasConfigs)
                    {
                        if (item.Value == _config)
                        {
                            UnHasConfigs.Remove(item);
                            HasConfigs.Add(item);
                            break;
                        }
                    }                 
                }                             
                ViewBag.UnHasConfigs = UnHasConfigs;
                ViewBag.HasConfigs = HasConfigs;
            }
            ViewBag.Attrs = _listItems;
            return View();
        }
        
        public ActionResult PageList(int? siliconCarbideId, DateTime start, DateTime end, string objs, int? pageNumber, int? pageSize, int? order)
        {
            Paging<SiliconCutting> _pagingSiliconCutting = new Paging<SiliconCutting>();
            if (pageNumber != null && pageNumber > 0) _pagingSiliconCutting.PageIndex = (int)pageNumber + 1;
            if (pageSize != null && pageSize > 0) _pagingSiliconCutting.PageSize = (int)pageSize;
            SiliconCutting sc = new SiliconCutting();
            if (!string.IsNullOrEmpty(objs))
            {
                sc = JsonDeserialize<SiliconCutting>(objs);
            }
            var _paging = scm.FindPageList(_pagingSiliconCutting, siliconCarbideId, start, end, sc, null);
            return Json(new { total = _paging.TotalNumber, rows = _paging.Items});
        }

        public ActionResult virableList()
        {
            if (RedisHelper.Get<List<System.Collections.Hashtable>>("ht_virables") == null || RedisHelper.Get<List<System.Collections.Hashtable>>("permissionList").Count() == 0)
                return Json(new { msg = "no data,no result!" },JsonRequestBehavior.AllowGet);
            else
            {
                var ht_virables = RedisHelper.Get<List<System.Collections.Hashtable>>("ht_virables");
                return Json(ht_virables, JsonRequestBehavior.AllowGet);
            }
        }
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }


        public ActionResult Detail(int id)
        {
            return View(scm.Find(id));
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="sc">模型</param>
        /// <param name="flag">是否和个人配置保持一致</param>
        /// <returns></returns>
        public FileResult ExportList(DateTime start, DateTime end, SiliconCutting sc)
        {
            var q = scm.FindList();
            var _where = LinqKit.PredicateBuilder.New<SiliconCutting>(true);
            if (start != null)
            {
                _where = _where.And(u => u.CuttingDate >= start);
            }
            if (end != null)
            {
                _where = _where.And(u => u.CuttingDate <= end);
            }
            if (sc != null)
            {
                #region 硅片切割的检索条件,真特么多。。。！
                if (sc.SiliconCuttingID > 0)
                    _where = _where.And(u => u.SiliconCuttingID == sc.SiliconCuttingID);
                if (sc.BottomMaterialLength > 0)
                    _where = _where.And(u => u.BottomMaterialLength == sc.BottomMaterialLength);
                if (sc.BreakedID > 0)
                    _where = _where.And(u => u.BreakedID == sc.BreakedID);
                if (!string.IsNullOrEmpty(sc.Checker))
                    _where = _where.And(u => u.Checker == sc.Checker);
                if (!string.IsNullOrEmpty(sc.CleaningEquipmentNum))
                    _where = _where.And(u => u.CleaningEquipmentNum == sc.CleaningEquipmentNum);
                if (sc.CuttingBlock > 0)
                    _where = _where.And(u => u.CuttingBlock == sc.CuttingBlock);
                if (sc.CuttingID > 0)
                    _where = _where.And(u => u.CuttingID == sc.CuttingID);
                if (sc.CuttingLength > 0)
                    _where = _where.And(u => u.CuttingLength == sc.CuttingLength);
                if (!string.IsNullOrEmpty(sc.CuttingNum))
                    _where = _where.And(u => u.CuttingNum == sc.CuttingNum);
                if (sc.CuttingSpecification > 0)
                    _where = _where.And(u => u.CuttingSpecification == sc.CuttingSpecification);
                if (sc.CuttingThickness > 0)
                    _where = _where.And(u => u.CuttingThickness == sc.CuttingThickness);
                if (!string.IsNullOrEmpty(sc.CuttingType))
                    _where = _where.And(u => u.CuttingType == sc.CuttingType);
                if (sc.DebrisWeight > 0)
                    _where = _where.And(u => u.DebrisWeight == sc.DebrisWeight);
                if (!string.IsNullOrEmpty(sc.EmployeeNum))
                    _where = _where.And(u => u.EmployeeNum == sc.EmployeeNum);
                if (sc.EquipmentFileID > 0)//这个可能要变动
                    _where = _where.And(u => u.EquipmentFileID == sc.EquipmentFileID);
                if (sc.GuideNum > 0)
                    _where = _where.And(u => u.GuideNum == sc.GuideNum);
                if (!string.IsNullOrEmpty(sc.Handler))
                    _where = _where.And(u => u.Handler == sc.Handler);
                //if (sc.IsBreaked >= 0)
                //    _where = _where.And(u => u.IsBreaked == sc.IsBreaked);
                //if (sc.IsCheck >= 0)
                //    _where = _where.And(u => u.IsCheck == sc.IsCheck);
                //if (sc.IsIncludedAssessment >= 0)
                //    _where = _where.And(u => u.IsIncludedAssessment == sc.IsIncludedAssessment);
                //if (sc.IsScrap >= 0)
                //    _where = _where.And(u => u.IsScrap == sc.IsScrap);
                //if (sc.IsSpotCheck >= 0)
                //    _where = _where.And(u => u.IsSpotCheck == sc.IsSpotCheck);
                //if (sc.IsTest >= 0)
                //    _where = _where.And(u => u.IsTest == sc.IsTest);
                if (sc.LevelOneCount > 0)
                    _where = _where.And(u => u.LevelOneCount == sc.LevelOneCount);
                if (sc.LevelOneTheoreticalCount > 0)
                    _where = _where.And(u => u.LevelOneTheoreticalCount == sc.LevelOneTheoreticalCount);
                if (sc.LevelThreeCount > 0)
                    _where = _where.And(u => u.LevelThreeCount == sc.LevelThreeCount);
                if (sc.LevelTwoCount > 0)
                    _where = _where.And(u => u.LevelTwoCount == sc.LevelTwoCount);
                if (!string.IsNullOrEmpty(sc.Pre_CleaningEquipmentNum))
                    _where = _where.And(u => u.Pre_CleaningEquipmentNum == sc.Pre_CleaningEquipmentNum);
                if (sc.PulpDensityEnd > 0)
                    _where = _where.And(u => u.PulpDensityEnd == sc.PulpDensityEnd);
                if (sc.PulpDensityStart > 0)
                    _where = _where.And(u => u.PulpDensityStart == sc.PulpDensityStart);
                if (sc.PulpUpdateCount > 0)
                    _where = _where.And(u => u.PulpUpdateCount == sc.PulpUpdateCount);
                if (sc.QualifiedCount > 0)
                    _where = _where.And(u => u.QualifiedCount == sc.QualifiedCount);
                if (!string.IsNullOrEmpty(sc.QualifiedRate))
                    _where = _where.And(u => u.QualifiedRate == sc.QualifiedRate);
                if (!string.IsNullOrEmpty(sc.Remark))
                    _where = _where.And(u => u.Remark == sc.Remark);
                if (sc.SiliconCarbideID > 0)
                    _where = _where.And(u => u.SiliconCarbideID == sc.SiliconCarbideID);
                if (sc.SlotPitch > 0)
                    _where = _where.And(u => u.SlotPitch == sc.SlotPitch);
                if (sc.SpotCheckCount > 0)
                    _where = _where.And(u => u.SpotCheckCount == sc.SpotCheckCount);
                if (!string.IsNullOrEmpty(sc.SpotChecker))
                    _where = _where.And(u => u.SpotChecker == sc.SpotChecker);
                if (!string.IsNullOrEmpty(sc.SpotCheckRemark))
                    _where = _where.And(u => u.SpotCheckRemark == sc.SpotCheckRemark);
                if (sc.SpotCheckUnqualifiedCount > 0)
                    _where = _where.And(u => u.SpotCheckUnqualifiedCount == sc.SpotCheckUnqualifiedCount);
                if (sc.SteelWireID > 0)
                    _where = _where.And(u => u.SteelWireID == sc.SteelWireID);
                if (sc.SumCount > 0)
                    _where = _where.And(u => u.SumCount == sc.SumCount);
                if (sc.SuspensionID > 0)
                    _where = _where.And(u => u.SuspensionID == sc.SuspensionID);
                if (sc.TeamID > 0)
                    _where = _where.And(u => u.TeamID == sc.TeamID);
                if (sc.UnqualifiedCount > 0)
                    _where = _where.And(u => u.UnqualifiedCount == sc.UnqualifiedCount);
                if (sc.WorkshopID > 0)
                    _where = _where.And(u => u.WorkshopID == sc.WorkshopID);
                #endregion
            }
            var result = q.Where(_where).ToList();
            var models = new List<SiliconCuttingReportModel> { };
            for (int i = 0; i < result.Count; i++)
            {
                #region
                models.Add(
                    new SiliconCuttingReportModel
                    {
                        SiliconCuttingID = result[i].SiliconCuttingID,
                        SliceQualityID = result[i].SliceQualityID,
                        WorkshopID = result[i].WorkshopID,
                        CuttingID = result[i].CuttingID,
                        CuttingNum = result[i].CuttingNum,
                        CuttingType = result[i].CuttingType,
                        EmployeeNum = result[i].EmployeeNum,
                        EquipmentFileID = result[i].EquipmentFileID,
                        CuttingSpecification = result[i].CuttingSpecification,
                        CuttingDate = result[i].CuttingDate,
                        CuttingBlock = result[i].CuttingBlock,
                        CuttingLength = result[i].CuttingLength,
                        CuttingThickness = result[i].CuttingThickness,
                        SiliconCarbideName = result[i].SiliconCarbide.Name,
                        SuspensionName = result[i].Suspension.Name,
                        PulpUpdateCount = result[i].PulpUpdateCount,
                        GuideNum = result[i].GuideNum,
                        QualifiedCount = result[i].QualifiedCount,
                        UnqualifiedCount = result[i].UnqualifiedCount,
                        QualifiedRate = result[i].QualifiedRate,
                        SteelWireName = result[i].SteelWire.Name,
                        SlotPitch = result[i].SlotPitch,
                        IsBreaked = result[i].IsBreaked > 0 ? "断线" : "未断线",
                        IsTest = result[i].IsTest > 0 ? "测试" : "未测试",
                        IsScrap = result[i].IsScrap > 0 ? "报废" : "未报废",
                        IsIncludedAssessment = result[i].IsIncludedAssessment > 0 ? "计入考核" : "不计入考核",
                        IsCheck = result[i].IsCheck > 0 ? "审核" : "未审核",
                        IsSpotCheck = result[i].IsSpotCheck > 0 ? "抽检" : "未抽检",
                        Remark = result[i].Remark
                    }
                 );
                #endregion
            }
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            Random rd = new Random();
            string filename = System.Convert.ToInt64(ts.TotalSeconds).ToString()+rd.Next(1000,9999);//以时间戳+随机数命名文件
            var exporter = new Chsword.Excel2Object.ExcelExporter();
            var bytes = exporter.ObjectToExcelBytes(models);
            return File(bytes, "application/ms-excel", filename + "_list.xls");
        }
    }
}